package com.common.utils;

import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class UrlUtils {

    public static final String ALLOWED_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*'()";

    public static String covertUrl(String url) {
        String urlPre = getPreUrl(url);
        Map<String, String> paramsMap = getUrlParameterReg(url);
        StringBuilder stringBuilder = new StringBuilder(urlPre).append("?");
        Set<String> keySet = paramsMap.keySet();
        for (String key : keySet) {
            try {
                stringBuilder.append(key).append("=").append(URLEncoder.encode(paramsMap.get(key), "utf-8")).append
                        ("&");
            } catch (UnsupportedEncodingException e) {
            }
        }
        if (keySet.size() > 0) {
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        }
        return stringBuilder.toString();
    }

    public static Map<String, String> getUrlParameterReg(String url) {
        Map<String, String> mapRequest = new HashMap<String, String>();

        String[] arrSplit = null;

        String strUrlParam = TruncateUrlPage(url);
        if (strUrlParam == null) {
            return mapRequest;
        }
        //每个键值为一组 www.2cto.com
        arrSplit = strUrlParam.split("[&]");
        for (String strSplit : arrSplit) {
            String[] arrSplitEqual = null;
            arrSplitEqual = strSplit.split("[=]");

            //解析出键值
            if (arrSplitEqual.length > 1) {
                //正确解析
                mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]);

            } else {
                if (arrSplitEqual[0] != "") {
                    //只有参数没有值，不加入
                    mapRequest.put(arrSplitEqual[0], "");
                }
            }
        }
        return mapRequest;
    }

    private static String TruncateUrlPage(String strURL) {
        String strAllParam = null;
        String[] arrSplit = null;
        strURL = strURL.trim();
        arrSplit = strURL.split("[?]");
        if (strURL.length() > 1) {
            if (arrSplit.length > 1) {
                if (arrSplit[1] != null) {
                    strAllParam = arrSplit[1];
                }
            }
        }
        return strAllParam;
    }

    private static String getPreUrl(String strURL) {
        strURL = strURL.trim();
        String[] arrSplit = strURL.split("[?]");
        if (strURL.length() > 1) {
            return arrSplit[0];
        }
        return strURL;
    }

    public static final String encodeURL(String url) {
        int index = url.indexOf("\\?");
        if (index < 0) {
            return url;
        }
        String urlPath = url.substring(0, index);
        String urlParamsString = url.substring(index, url.length() - 1);
        return url;
    }

    String[] splitUrl(String url, String seperator) {
        int index = url.indexOf(seperator);
        String urlPath = url.substring(0, index);
        String urlParamsString = url.substring(index, url.length() - 1);
        return new String[]{urlPath, urlParamsString};
    }

    /**
     * urlDeCode转码
     *
     * @return
     */
    public static String urlDeCode(String string) {
        if (string == null || string.isEmpty()) {
            return "";
        }
        String str1 = "";
        try {
            str1 = URLDecoder.decode(string, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str1;
    }


    public static String encodeURI(String str) throws UnsupportedEncodingException {
        String isoStr = new String(str.getBytes("UTF8"), "ISO-8859-1");
        char[] chars = isoStr.toCharArray();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < chars.length; i++) {
            if ((chars[i] <= 'z' && chars[i] >= 'a') || (chars[i] <= 'Z' && chars[i] >= 'A')
                    || chars[i] == '-' || chars[i] == '_' || chars[i] == '.' || chars[i] == '!'
                    || chars[i] == '~' || chars[i] == '*' || chars[i] == '\'' || chars[i] == '('
                    || chars[i] == ')' || chars[i] == ';' || chars[i] == '/' || chars[i] == '?'
                    || chars[i] == ':' || chars[i] == '@' || chars[i] == '&' || chars[i] == '='
                    || chars[i] == '+' || chars[i] == '$' || chars[i] == ',' || chars[i] == '#'
                    || (chars[i] <= '9' && chars[i] >= '0')) {
                sb.append(chars[i]);
            } else {
                sb.append("%");
                sb.append(Integer.toHexString(chars[i]));
            }
        }
        return sb.toString();
    }

    /**
     * Description:
     *
     * @param input
     * @return
     * @see
     */
    public static String encodeURIComponent(String input) {
        if (null == input || "".equals(input.trim())) {
            return input;
        }
        int l = input.length();
        StringBuilder o = new StringBuilder(l * 3);
        try {
            for (int i = 0; i < l; i++) {
                String e = input.substring(i, i + 1);
                if (ALLOWED_CHARS.indexOf(e) == -1) {
                    byte[] b = e.getBytes("utf-8");
                    o.append(getHex(b));
                    continue;
                }
                o.append(e);
            }
            return o.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return input;
    }

    private static String getHex(byte buf[]) {
        StringBuilder o = new StringBuilder(buf.length * 3);
        for (int i = 0; i < buf.length; i++) {
            int n = (int) buf[i] & 0xff;
            o.append("%");
            if (n < 0x10) {
                o.append("0");
            }
            o.append(Long.toString(n, 16).toUpperCase());
        }
        return o.toString();
    }

    public static String getUrlHost(String remoteUrl) {
        URL url = null;
        if (StringUtils.isBlank(remoteUrl)) {
            return "";
        }
        try {
            url = new URL(remoteUrl);
        } catch (MalformedURLException e) {
            return "";
        }
        return url.getHost();
    }

}
